package com.example.lib_common.utils

import android.content.Context
import com.tencent.mmkv.MMKV
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * @author: njb
 * @date: 2023/8/9 22:40
 * @desc:
 */
class MMKVUtil private constructor(){
    lateinit var mmKv:MMKV
    companion object {
        const val DATE_FORMAT = "yyyy-MM-dd HH.mm.ss"
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { MMKVUtil() }
    }

    fun init(context: Context) {
        //第一种使用mmkv默认目录
        //MMKV.initialize(context)
        //第二种使用自定义包名目录
         //MMKV.initialize(context, FileManager.getStorageRootDir() + FileManager.MMKV_DIR)

        val mFileDateFormat = SimpleDateFormat(DATE_FORMAT, Locale.US)
        //视频保存路径
        val file =
            File(FileManager.getMMKVPath(), mFileDateFormat.format(Date()) + "/mmkv")
        //第三种使用自定义的系统目录 dcim、download、music其中一个即可
        MMKV.initialize(context,file.absolutePath)
        mmKv = MMKV.mmkvWithID("MyMMKVTestID", MMKV.MULTI_PROCESS_MODE)
        mmKv.encode("bool", true)
    }

    fun initTest(context: Context) {
        //第一种使用mmkv默认目录
        //MMKV.initialize(context)
        //第二种使用自定义包名目录
        MMKV.initialize(context, FileManager.getStorageRootDir() + FileManager.MMKV_DIR)
        //第三种使用自定义的系统目录 dcim、download、music其中一个即可
        //MMKV.initialize(context,FileManager.getMMKVPath())
        mmKv = MMKV.mmkvWithID("MyTestID", MMKV.MULTI_PROCESS_MODE)
        mmKv.encode("bool", true)
    }

    fun encode(key: String, value: Any) {
        when (value) {
            is String -> mmKv.encode(key, value)
            is Int -> mmKv.encode(key, value)
            is Boolean -> mmKv.encode(key, value)
            is Long -> mmKv.encode(key, value)
            is Float -> mmKv.encode(key, value)
            is Double -> mmKv.encode(key, value)
        }
    }

    inline fun <reified T> decode(key: String, defaultValue: T): T = when (T::class) {
        String::class -> mmKv.decodeString(key, defaultValue as String?) as T
        Int::class -> mmKv.decodeInt(key, defaultValue as Int) as T
        Boolean::class -> mmKv.decodeBool(key, defaultValue as Boolean) as T
        Long::class -> mmKv.decodeLong(key, defaultValue as Long) as T
        Float::class -> mmKv.decodeFloat(key, defaultValue as Float) as T
        Double::class -> mmKv.decodeDouble(key, defaultValue as Double) as T
        else -> throw IllegalArgumentException("Unsupported type")
    }

    /**
     * 添加清空所有数据方法
     */
    fun clearAllData(){
        mmKv.clearAll()
    }
}